<template>
  <!-- 使用主布局容器 -->
  <main-layout
      :username="username"
      :unread-count="unreadCount"
  >
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/" class="breadcrumb mb-15">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 页面标题和操作区 -->
    <div class="page-header flex-between mb-15">
      <h2 class="page-title">用户管理</h2>
      <div class="header-actions flex-center">
        <el-input
            v-model="searchQuery"
            placeholder="搜索用户姓名/编号/手机号"
            prefix-icon="el-icon-search"
            style="width: 200px; margin-right: 10px"
            @keyup.enter.native="handleSearch"
        ></el-input>
        <el-button type="primary" icon="el-icon-plus" @click="handleAddUser">
          新增用户
        </el-button>
      </div>
    </div>

    <!-- 用户列表卡片 -->
    <el-card class="user-table" shadow="hover">
      <div slot="header" class="flex-between">
        <h3>用户列表</h3>
        <div class="table-actions flex-center">
          <el-select v-model="roleFilter" placeholder="角色筛选" @change="handleRoleFilter" class="mr-10">
            <el-option label="全部角色" value=""></el-option>
            <el-option label="系统管理员" value="系统管理员"></el-option>
            <el-option label="设备管理员" value="设备管理员"></el-option>
            <el-option label="工人" value="工人"></el-option>
            <el-option label="生产管理员" value="生产管理员"></el-option>
          </el-select>
          <el-select v-model="statusFilter" placeholder="状态筛选" @change="handleStatusFilter" class="mr-10">
            <el-option label="全部状态" value=""></el-option>
            <el-option label="默认" value="默认"></el-option>
            <el-option label="封禁" value="封禁"></el-option>
          </el-select>
          <el-button icon="el-icon-download" size="mini" @click="exportUserData">
            导出数据
          </el-button>
        </div>
      </div>

      <!-- 用户表格（按钮强制单行） -->
      <el-table
          :data="filteredUsers"
          stripe
          style="width: 100%"
          v-loading="tableLoading"
          :cell-style="cellStyle"
          :header-cell-style="headerCellStyle"
          highlight-current-row
      >
        <el-table-column type="index" label="序号" width="60"></el-table-column>
        <el-table-column prop="userId" label="用户编号" width="120"></el-table-column>
        <el-table-column prop="name" label="姓名" width="100"></el-table-column>
        <el-table-column prop="phone" label="手机号" width="140"></el-table-column>
        <el-table-column prop="status" label="账号状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === '默认' ? 'success' : 'danger'">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="email" label="邮箱号" width="180"></el-table-column>
        <el-table-column prop="idCard" label="身份证号" width="180">
          <template slot-scope="scope">
            {{ scope.row.idCard.replace(/(\d{6})\d{8}(\d{4})/, '$1********$2') }}
          </template>
        </el-table-column>
        <el-table-column prop="roleId" label="角色编号" width="120"></el-table-column>
        <el-table-column prop="roleName" label="角色名称" width="120"></el-table-column>
        <!-- 操作列：固定宽度+弹性容器确保按钮单行 -->
        <el-table-column label="操作" width="290" align="center">
          <template slot-scope="scope">
            <div class="btn-container"> <!-- 弹性容器包裹按钮 -->
              <el-button size="mini" type="primary" @click="viewUserDetail(scope.row)" class="table-btn">查看</el-button>
              <el-button size="mini" type="success" @click="editUser(scope.row)" class="table-btn">编辑</el-button>
              <el-button
                  size="mini"
                  type="danger"
                  @click="deleteUser(scope.row)"
                  :disabled="scope.row.status === '封禁'"
                  class="table-btn"
              >
                {{ scope.row.status === '封禁' ? '已封禁' : '删除' }}
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container mt-15">
        <el-pagination
            background
            layout="total, prev, pager, next, sizes"
            :total="filteredUsers.length"
            :page-sizes="[10, 20, 50]"
            :page-size="pageSize"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 新增/编辑用户对话框 -->
    <el-dialog
        :title="isEdit ? '编辑用户' : '新增用户'"
        :visible.sync="dialogVisible"
        width="600px"
        :close-on-click-modal="false"
        :modal-append-to-body="false"
        :append-to-body="true"
    >
      <el-form :model="form" :rules="rules" ref="userForm" label-width="120px">
        <el-form-item label="用户编号" prop="userId" v-if="isEdit">
          <el-input v-model="form.userId" disabled></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone"></el-input>
        </el-form-item>
        <el-form-item label="账号状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择账号状态">
            <el-option label="默认" value="1"></el-option>
            <el-option label="封禁" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="邮箱号" prop="email">
          <el-input v-model="form.email"></el-input>
        </el-form-item>
        <el-form-item label="身份证号" prop="idCard">
          <el-input v-model="form.idCard" placeholder="18位身份证号"></el-input>
        </el-form-item>
        <el-form-item label="账号密码" prop="password" v-if="!isEdit">
          <el-input v-model="form.password" type="password" placeholder="初始密码至少8位"></el-input>
        </el-form-item>
        <el-form-item label="角色名称" prop="roleName">
          <el-select v-model="form.roleName" placeholder="请选择角色" @change="handleRoleChange">
            <el-option label="系统管理员" value="系统管理员"></el-option>
            <el-option label="设备管理员" value="设备管理员"></el-option>
            <el-option label="工人" value="工人"></el-option>
            <el-option label="生产管理员" value="生产管理员"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="角色编号" prop="roleId" v-if="isEdit">
          <el-input v-model="form.roleId" disabled></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>

    <!-- 用户详情对话框 -->
    <el-dialog
        title="用户详情"
        :visible.sync="detailVisible"
        width="700px"
        :close-on-click-modal="false"
        :modal-append-to-body="false"
        :append-to-body="true"
    >
      <div class="user-detail">
        <div class="detail-header flex-center mb-15">
          <el-avatar :size="80" class="detail-avatar">
            <span>{{ selectedUser.name ? selectedUser.name.charAt(0) : '' }}</span>
          </el-avatar>
          <div class="detail-header-info ml-15">
            <h3 class="detail-name">{{ selectedUser.name }}</h3>
            <p class="detail-role">{{ selectedUser.roleName }}（{{ selectedUser.roleId }}）</p>
            <el-tag :type="selectedUser.status === '1' ? 'success' : 'danger'" class="mt-5">
              {{ selectedUser.status }}
            </el-tag>
          </div>
        </div>

        <el-descriptions column="2" border class="detail-descriptions">
          <el-descriptions-item label="用户编号">{{ selectedUser.userId }}</el-descriptions-item>
          <el-descriptions-item label="姓名">{{ selectedUser.name }}</el-descriptions-item>
          <el-descriptions-item label="手机号">{{ selectedUser.phone }}</el-descriptions-item>
          <el-descriptions-item label="账号状态">{{ selectedUser.status }}</el-descriptions-item>
          <el-descriptions-item label="邮箱号">{{ selectedUser.email }}</el-descriptions-item>
          <el-descriptions-item label="身份证号">
            {{ selectedUser.idCard ? selectedUser.idCard.replace(/(\d{6})\d{8}(\d{4})/, '$1********$2') : '' }}
          </el-descriptions-item>
          <el-descriptions-item label="账号密码">{{ '********' }}</el-descriptions-item>
          <el-descriptions-item label="角色编号">{{ selectedUser.roleId }}</el-descriptions-item>
          <el-descriptions-item label="角色名称" :span="2">{{ selectedUser.roleName }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <div slot="footer">
        <el-button @click="detailVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </main-layout>
</template>

<script>
import MainLayout from '../../components/layout/MainLayout.vue';
import axios from "axios";

export default {
  components: { MainLayout },
  data() {
    return {
      username: '管理员',
      unreadCount: 3,
      searchQuery: '',
      roleFilter: '',
      statusFilter: '',
      users: [
        { userId: 'USR001', name: '张系统', phone: '13800138001', status: '默认', email: 'sys.zhang@example.com', idCard: '110101199001011234', password: 'Sys@123456', roleId: 'ROL001', roleName: '系统管理员' },
        { userId: 'USR002', name: '李设备', phone: '13900139002', status: '默认', email: 'device.li@example.com', idCard: '310101199202022345', password: 'Dev@654321', roleId: 'ROL002', roleName: '设备管理员' },
        { userId: 'USR003', name: '王工人', phone: '13700137003', status: '默认', email: 'worker.wang@example.com', idCard: '440101198803033456', password: 'Wkr@112233', roleId: 'ROL003', roleName: '工人' },
        { userId: 'USR004', name: '赵生产', phone: '13600136004', status: '默认', email: 'prod.zhao@example.com', idCard: '220101199504044567', password: 'Pro@445566', roleId: 'ROL004', roleName: '生产管理员' },
        { userId: 'USR005', name: '钱工人', phone: '13500135005', status: '封禁', email: 'worker.qian@example.com', idCard: '510101199305055678', password: 'Wkr@667788', roleId: 'ROL003', roleName: '工人' },
        { userId: 'USR006', name: '孙设备', phone: '13400134006', status: '默认', email: 'device.sun@example.com', idCard: '610101198506066789', password: 'Dev@998877', roleId: 'ROL002', roleName: '设备管理员' },
        { userId: 'USR007', name: '周系统', phone: '13300133007', status: '默认', email: 'sys.zhou@example.com', idCard: '710101198907077890', password: 'Sys@332211', roleId: 'ROL001', roleName: '系统管理员' },
        { userId: 'USR008', name: '吴生产', phone: '13200132008', status: '封禁', email: 'prod.wu@example.com', idCard: '810101199108088901', password: 'Pro@778899', roleId: 'ROL004', roleName: '生产管理员' }
      ],
      filteredUsers: [],
      tableLoading: false,
      pageSize: 10,
      currentPage: 1,
      dialogVisible: false,
      detailVisible: false,
      isEdit: false,

      form: {
        userId: '',
        name: '',
        phone: '',
        status: '1',//1表示默认，0表示封禁
        email: '',
        idCard: '',
        password: '',
        roleId: '',
        roleName: ''
      },
      userData:{
        viewName:'',
        operation:'',
        opType:'',
        data:'',
      },
      selectedUser: {},
      rules: {
        name: [
          { required: true, message: '请输入用户姓名', trigger: 'blur' },
          { min: 2, max: 10, message: '姓名长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的11位手机号', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择账号状态', trigger: 'change' }
        ],
        email: [
          { required: true, message: '请输入邮箱号', trigger: 'blur' },
          { pattern: /^[\w.-]+@[a-zA-Z0-9-]+\.[a-zA-Z]+$/, message: '请输入正确的邮箱格式', trigger: 'blur' }
        ],
        idCard: [
          { required: true, message: '请输入身份证号', trigger: 'blur' },
          { pattern: /^\d{18}$/, message: '请输入18位身份证号', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请设置账号密码', trigger: 'blur' },
          { min: 8, message: '密码长度至少8位', trigger: 'blur' }
        ],
        roleName: [
          { required: true, message: '请选择角色名称', trigger: 'change' }
        ]
      }
    };
  },
  methods: {
    cellStyle() {
      return { 'font-size': '14px', 'padding': '12px 0' };
    },
    headerCellStyle() {
      return { 'background-color': '#f0f9e8', 'color': '#2e7d32', 'font-weight': '500', 'padding': '12px 0' };
    },
    getRoleIdByRoleName(roleName) {
      const roleMap = { '系统管理员': 'ROL001', '设备管理员': 'ROL002', '工人': 'ROL003', '生产管理员': 'ROL004' };
      return roleMap[roleName] || '';
    },
    handleSearch() { this.filterUsers(); },
    handleRoleFilter() { this.filterUsers(); },
    handleStatusFilter() { this.filterUsers(); },
    filterUsers() {
      this.tableLoading = true;
      setTimeout(() => {
        this.filteredUsers = this.users.filter(user => {
          const matchesSearch = !this.searchQuery || user.name.includes(this.searchQuery) || user.userId.includes(this.searchQuery) || user.phone.includes(this.searchQuery);
          const matchesRole = !this.roleFilter || user.roleName === this.roleFilter;
          const matchesStatus = !this.statusFilter || user.status === this.statusFilter;
          return matchesSearch && matchesRole && matchesStatus;
        });
        this.tableLoading = false;
      }, 300);
    },
    handleSizeChange(val) { this.pageSize = val; this.currentPage = 1; },
    handleCurrentChange(val) { this.currentPage = val; },
    handleRoleChange() { this.form.roleId = this.getRoleIdByRoleName(this.form.roleName); },
    handleAddUser() {
      this.isEdit = false;
      this.form = { userId: '', name: '', phone: '', status: '默认', email: '', idCard: '', password: '', roleId: '', roleName: '' };
      this.dialogVisible = true;
    },
    viewUserDetail(row) { this.selectedUser = { ...row }; this.detailVisible = true; },
    editUser(row) { this.isEdit = true; this.form = { ...row }; this.dialogVisible = true; },
    deleteUser(row) {
      this.$confirm(`确定要删除用户 ${row.name}（${row.userId}）吗?`, '提示', { type: 'warning' }).then(() => {
        const index = this.users.findIndex(user => user.userId === row.userId);
        if (index !== -1) { this.users.splice(index, 1); this.filterUsers(); this.$message.success('删除成功'); }
      }).catch(() => {});
    },

    submitForm() {
      this.$refs.userForm.validate((valid) => {
        if (valid) {
          this.userData.data=this.form;
          if (this.isEdit){
            this.userData.opType=1;//编辑操作待修改
            this.userData.operation='user_update';
            this.userData.viewName='userManagement';
          }else {
            this.userData.opType=1;//增加操作
            this.userData.operation='user_insert';
            this.userData.viewName='userManagement';
          }
          //发送消息
          axios({
            method: 'post',
            url: '/teaSystem/TeaProcessingServlet',
            headers: {
              'Content-Type': 'application/json',  // 明确指定JSON格式
              // 可根据需要添加其他请求头，例如认证信息
              // 'Authorization': 'Bearer your-token'
            },
            data:this.userData
          }).then(res => {
            if (res.status === 200) {
              if(this.isEdit)
                this.$message.success('编辑成功');
              else{
                this.$message.success('新增成功');
              }
            }
          }).catch(error => {
            // 建议添加错误处理
            this.$message.error('请求失败：' + (error.response?.data?.message || error.message));
          });
          this.filterUsers();
          this.dialogVisible = false;
        }
      });
    },
    exportUserData() {
      this.$confirm('确定要导出用户数据吗?', '提示', { type: 'info' }).then(() => {
        this.tableLoading = true;
        setTimeout(() => { this.tableLoading = false; this.$message.success('用户数据导出成功'); }, 800);
      }).catch(() => {});
    }
  },
  mounted() { this.filterUsers(); }
};
</script>

<style lang="scss" scoped>
@use '@/assets/styles/variables' as *;

// 用户详情样式
.user-detail { padding: 10px 0; }
.detail-header { align-items: center; }
.detail-avatar { background-color: $primary-color; color: #fff; font-size: 32px; }
.detail-header-info { flex: 1; }
.detail-name { font-size: 20px; font-weight: 600; margin: 0 0 5px 0; }
.detail-role { color: $text-secondary; margin: 0 0 5px 0; }
.detail-descriptions {
  margin-top: 15px;
  .el-descriptions__label { font-weight: 500; color: $text-primary; }
}

// 核心：按钮强制单行布局
.btn-container {
  display: flex !important;       // 弹性布局
  align-items: center !important; // 垂直居中
  justify-content: center !important; // 水平居中
  width: 100% !important;         // 占满单元格宽度
  white-space: nowrap !important; // 禁止容器内换行
}

// 按钮统一样式
::v-deep .table-btn {
  width: 65px !important;         // 固定按钮宽度（足够容纳文字）
  margin-right: 8px !important;   // 按钮间距
  padding: 8px 0 !important;      // 统一内边距
  white-space: nowrap !important; // 禁止按钮文字换行
}

// 移除最后一个按钮的右间距
::v-deep .table-btn:last-child { margin-right: 0 !important; }

// 响应式调整
@media (max-width: 992px) { .detail-descriptions { column-count: 2 !important; } }
@media (max-width: 768px) { .detail-descriptions { column-count: 1 !important; } }
</style>